package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.config.SignUtil;
import com.jsb.laundry.service.OfficialAccountService;
import com.jsb.laundry.utils.RedisUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 微信公众号入口
 */
@Api(tags = {"微信公众号入口"})
@RestController
@RequestMapping("/system/")
public class OfficialAccountController {
    private static final Logger LOGGER = LoggerFactory.getLogger(OfficialAccountController.class);
    @Resource
    private OfficialAccountService officialAccountService;
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 获取微信公众号的token
     */
    public String getOfficialAccessToken() {
        /**
         * 获取access_token
         * https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html 第三方接口地址
         */
        //获取token
        String token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa808024765c753cb&secret=7333cc2d01b75703f350f4a1aa6cdf4d";
        String sendGet = HttpUtil.sendGet(token, null, null, null);
        String access_token = JSONObject.parseObject(sendGet).getString("access_token");
        LOGGER.info("获取微信公众号access_token:" + access_token);

        redisUtil.setCacheObject("wx_official_access_token", access_token, 1, TimeUnit.HOURS); //1小时过期
        return access_token;
    }
    @RequestMapping(value = "config")
    public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Enumeration pNames = request.getParameterNames();
        while (pNames.hasMoreElements()) {
            String name = (String) pNames.nextElement();
            String value = request.getParameter(name);
            // out.print(name + "=" + value);
            String log = "name =" + name + "     value =" + value;
        }
        String signature = request.getParameter("signature");/// 微信加密签名
        String timestamp = request.getParameter("timestamp");/// 时间戳
        String nonce = request.getParameter("nonce"); /// 随机数
        String echostr = request.getParameter("echostr"); // 随机字符串
        PrintWriter out = response.getWriter();


        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            LOGGER.info("校验成功");
            out.print(echostr);
        }

        //获取关注事件
        String fromXml = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        if (!JSBUtil.isEmptyString(fromXml)) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputStream inputStream = new ByteArrayInputStream(fromXml.getBytes());
            Document document = builder.parse(inputStream);

            Element root = document.getDocumentElement();
            NodeList nodeList = root.getChildNodes();
            HashMap<String, String> hashMap = new HashMap();

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
//                    System.out.println(node.getNodeName() + ": " + node.getTextContent());
                    hashMap.put(node.getNodeName(), node.getTextContent());
                }

                out.print(echostr);
            }
            String fromUserName = hashMap.get("FromUserName");//OpenID
            String Event = hashMap.get("Event");//事件类型，subscribe(订阅)、unsubscribe(取消订阅)
            //根据公众号的openid查询unionid
            String accessToken = redisUtil.getCacheObject("wx_official_access_token");
            if (JSBUtil.isEmptyString(accessToken)){
                String officialAccessToken = getOfficialAccessToken();
                accessToken = officialAccessToken;
            }
            //获取公众号UNIONID
            String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + fromUserName + "&lang=zh_CN";
            LOGGER.error("请求参数" + hashMap);
            String get = HttpUtil.sendGet(url, null, null, null);
            String unionid = JSONObject.parseObject(get).getString("unionid");
            int byOpenID = officialAccountService.findByOpenID(fromUserName);
            int byDel = officialAccountService.findByDel(fromUserName);
            if ("subscribe".equals(Event)) {
                if (byOpenID == 1) {
                    officialAccountService.updAccount(fromUserName, "0");
                    officialAccountService.updateUnionId(unionid, fromUserName);
                }
                if (byOpenID == 0) {
                    officialAccountService.addAccount(unionid, fromUserName);
                }
            }
            if ("unsubscribe".equals(Event)) {
                officialAccountService.updAccount(fromUserName, "1");
                officialAccountService.updateUnionId(unionid, fromUserName);
            }
        }


        out.close();
        out = null;

    }
}
